<template>
  <div class="atrs-box">
    <!-- 文章列表 -->
    <van-pull-refresh
      v-model="refreshing"
      @refresh="onRefresh"
      success-text="刷新成功"
    >
      <van-list
        v-model="loading"
        :finished="finished"
        :error.sync="error"
        finished-text="没有更多了"
        error-text="请求失败，点击重新加载"
        @load="onLoad"
      >
        <van-cell
          v-for="item in list"
          :key="item.art_id"
          :title="item.title"
          :to="`/atrcle/${item.art_id}`"
        >
          <template #label>
            <span style="padding-right: 6px">{{ item.aut_name }}</span>
            <span style="padding-right: 6px">点赞:{{ item.comm_count }}</span>
            <span>{{ item.pubdate | relativeTime }}</span>
          </template>
          <template v-slot:extra>
            <van-image
              width="50"
              height="50"
              :src="imge"
              v-for="(imge, index) in item.cover.images"
              :key="index"
            />
          </template>
        </van-cell>
      </van-list>
    </van-pull-refresh>
    <!-- 文章列表 -->
  </div>
</template>

<script>
import { atrs } from "@/api/user.js";
export default {
  props: {
    channel: {
      type: Object,
      required: true,
    },
  },
  data() {
    return {
      list: [], // 文章数据
      loading: false, //间断数据加载状态
      finished: false, //完成数据全部加载判断
      timestamp: null, //获取文章时间搓
      error: false, //控制失败提示按钮
      refreshing: false,
    };
  },
  //   created(){
  //       this.getAtrs()
  //   },
  methods: {
    //   获取文章数据
    async onLoad() {
      // console.log('文章');
      // 1.异步获取数据
      try {
        const { data: res } = await atrs(
          this.channel.id,
          this.timestamp || new Date()
        );
        // console.log(res);
        // 3.间断数据加载状态结束
        this.loading = false;

        console.log(res);
        //4. 判断数据全部加载完成
        if (res.data.results.length >= 10) {
          //   更新时间戳
          this.timestamp = res.data.pre_timestamp;
        } else {
          this.finished = true;
        }
        this.list.push(...res.data.results);
      } catch (err) {
        this.error = true;
        this.loading = false;
        console.log(err, "获取失败");
      }
    },
    // 上拉刷新
    async onRefresh() {
      try {
        const { data: res } = await atrs(
          this.channel.id,
          this.timestamp || new Date()
        );
        if (this.timestamp == res.data.pre_timestamp) {
          return;
        } else {
          this.list.unshift(...res.data.results);
          this.refreshing = false;
        }
      } catch {
        this.error = true;
      }
    },
  },
};
</script>

<style>
</style>